// LoginPage.tsx  
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import { Form, Input, Button, Alert } from 'antd';

const LoginPage: React.FC = () => {
    const [username, setUsername] = useState<string>('');
    const [password, setPassword] = useState<string>('');
    const [error, setError] = useState<string>('');
    const [loading, setLoading] = useState<boolean>(false);
    const navigate = useNavigate(); // Hook to get navigation function  

    const handleLogin = async (values: { username: string; password: string }) => {
        setError('');
        setLoading(true);

        const apiUrl = process.env.REACT_APP_API_URL;

        try {
            const response = await axios.post<{ token: string }>(`${apiUrl}/login`, {
                username: values.username,
                password: values.password,
            });
            localStorage.setItem('token', response.data.token);
            alert('登录成功！');
            navigate('/home_page'); // 登录成功后跳转到导航页面  
        } catch (err) {
            setError('用户名或密码错误');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div style={{ maxWidth: '400px', margin: '100px auto', padding: '20px', border: '1px solid #d9d9d9', borderRadius: '8px', boxShadow: '0 2px 4px rgba(0,0,0,0.1)' }}>
            <h2 style={{ textAlign: 'center' }}>登录</h2>
            {error && <Alert message={error} type="error" showIcon />}
            <Form layout="vertical" onFinish={handleLogin} style={{ marginTop: '20px' }}>
                <Form.Item label="用户名" name="username" rules={[{ required: true, message: '请输入用户名!' }]}>
                    <Input value={username} onChange={(e) => setUsername(e.target.value)} placeholder="请输入用户名" />
                </Form.Item>

                <Form.Item label="密码" name="password" rules={[{ required: true, message: '请输入密码!' }]}>
                    <Input.Password value={password} onChange={(e) => setPassword(e.target.value)} placeholder="请输入密码" />
                </Form.Item>

                <Form.Item>
                    <Button type="primary" htmlType="submit" disabled={loading} loading={loading} style={{ width: '100%' }}>
                        登录
                    </Button>
                </Form.Item>
            </Form>
        </div>
    );
};

export default LoginPage;